# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import os
import json
import logging

from abc import ABCMeta, abstractmethod
from agent.common.config import Config

logger = logging.getLogger('common')

"""
Feature basic class

"""

class Feature(metaclass=ABCMeta):
    def __init__(self, domain_name, feature_name):
        """ Check if the feature is available.
        
        Raises:
            Exception: feature unavailable
        """
        self.domain_name = domain_name
        self.feature_name= feature_name
    
    @abstractmethod
    def set_value(self, value):
        """ value setting method of this feature

        Raises:
            Exception: value setting failed
        """
        pass
    
    @abstractmethod
    def get_value(self):        
        """ value reading method of this feature

        Raises:
            Exception: value reading failed
        """
        pass
    
    def rollback(self):
        """ backup value for this feature
        
        Raises:
            Exception: backup failed
        """
        backup_file = os.path.join(
            Config.BACKUP_PATH, "{}_{}.json".format(self.domain_name, self.feature_name))
        if not os.path.exists(backup_file):
            return
        
        logger.info("load backup data from: {}".format(backup_file))
        value = json.load(open(backup_file))
        self.set_value(value)
        os.remove(backup_file)
            
    def backup(self):
        self.rollback()
        backup_file = os.path.join(
            Config.BACKUP_PATH, "{}_{}.json".format(self.domain_name, self.feature_name))
    
        try:
            value = self.get_value()
            
        except Exception as e:
            logger.error("failed to read param: {}".format(e))
            raise e

        with open(backup_file, "w") as f:
            f.write(json.dumps(value))
            
        logger.info("backup '{}:{}' value: {}".format(self.domain_name, self.feature_name, value))
        return value